package com.cn.onetrip.adapter;

import java.util.ArrayList;
import java.util.List;
import java.util.Vector;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cn.onetrip.activity.R;
import com.cn.onetrip.objects.ArticleObj;
import com.cn.onetrip.untility.DebugUtil;
import com.cn.onetrip.untility.ImageUtils;
import com.cn.onetrip.untility.SBCToDBC;
import com.cn.onetrip.untility.SyncImageLoader;
import com.cn.onetrip.untility.SyncImageLoader.OnImageLoadListener;

public class TravelDetailItemAdapter extends BaseAdapter {

	public Vector<ArticleObj> mModels = new Vector<ArticleObj>();
	private LayoutInflater mInflater;
	private Context mContext;
	private ListView mListView;
	private Handler mhandler;
	private SyncImageLoader syncImageLoader;

	private List<ImageView> imageViewsList = new ArrayList<ImageView>();

	public TravelDetailItemAdapter(Context context, ListView listView,
			Handler handler) {
		mInflater = LayoutInflater.from(context);
		syncImageLoader = new SyncImageLoader(context);
		mContext = context;
		mListView = listView;
		mhandler = handler;
		mListView.setOnScrollListener(onScrollListener);

	}

	public void addBooks(String title, String imageUrl, String contentText) {
		ArticleObj model = new ArticleObj();
		model.title = title;
		model.icon = imageUrl;
		model.description = contentText;
		mModels.add(model);
	}

	public void clean() {
		mModels.clear();
	}

	public void threadQuit() {
		if (syncImageLoader != null) {
			syncImageLoader.threadQuit();
			syncImageLoader = null;
		}
	}

	public void clear() {
		for (int i = 0; i < imageViewsList.size(); i++) {
			ImageView imageView = imageViewsList.get(i);
			imageView.setBackgroundDrawable(null);
			System.gc();
		}
		imageViewsList.clear();
	}

	@Override
	public int getCount() {
		int size = mModels.size();
		return mModels.size();
	}

	@Override
	public Object getItem(int position) {
		if (position >= getCount()) {
			return null;
		}
		return mModels.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		final ArticleObj model = mModels.get(position);

		convertView = mInflater
				.inflate(R.layout.travel_detail_list_items, null);
		RelativeLayout layoutTravelImage = (RelativeLayout) convertView
				.findViewById(R.id.layout_travel_image);
		RelativeLayout TravelTextBg = (RelativeLayout) convertView
				.findViewById(R.id.TravelTextBg);
		TextView travelDate = (TextView) convertView
				.findViewById(R.id.TravelDetailDate);
		ImageView travelImage = (ImageView) convertView
				.findViewById(R.id.TravelDetailImage);
		TextView travelContentText = (TextView) convertView
				.findViewById(R.id.TravelDetailContent);
		ImageView travelLineDown = (ImageView) convertView
				.findViewById(R.id.TravelLineDown);

		convertView.setTag(position);

		travelDate.setText(model.title);
		travelContentText.setText(SBCToDBC.ToDBC(model.description));
		if (position == mModels.size() - 1) {
			travelLineDown.setVisibility(View.GONE);
		}

		travelImage.setBackgroundResource(R.drawable.default_image_big);
		if (model.icon.equals("") || model.icon == null) {
			RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams) TravelTextBg
					.getLayoutParams();
			Params.topMargin = 0;
			TravelTextBg.setLayoutParams(Params);
			layoutTravelImage.setVisibility(View.GONE);
		} else {
			syncLoadImage(travelImage, model);
		}

		// final ViewHolder viewHolder;
		// if (convertView == null) {
		// viewHolder = new ViewHolder();
		// convertView = mInflater.inflate(R.layout.travel_detail_list_items,
		// null);
		// viewHolder.layoutTravelImage = (RelativeLayout) convertView
		// .findViewById(R.id.layout_travel_image);
		// viewHolder.TravelTextBg = (RelativeLayout) convertView
		// .findViewById(R.id.TravelTextBg);
		// viewHolder.travelDate = (TextView) convertView
		// .findViewById(R.id.TravelDetailDate);
		// viewHolder.travelImage = (ImageView) convertView
		// .findViewById(R.id.TravelDetailImage);
		// viewHolder.travelContentText = (TextView) convertView
		// .findViewById(R.id.TravelDetailContent);
		// viewHolder.travelLineDown = (ImageView) convertView
		// .findViewById(R.id.TravelLineDown);
		// imageViewsList.add(viewHolder.travelImage);
		//
		// convertView.setTag(viewHolder);
		// } else {
		// viewHolder = (ViewHolder) convertView.getTag();
		// }
		//
		// viewHolder.travelDate.setText(model.title);
		// viewHolder.travelContentText.setText(SBCToDBC.ToDBC(model.description));
		// if (position == mModels.size() - 1) {
		// viewHolder.travelLineDown.setVisibility(View.GONE);
		// }
		//
		// viewHolder.travelImage
		// .setBackgroundResource(R.drawable.default_image_big);
		// if (model.icon.equals("") || model.icon == null) {
		// RelativeLayout.LayoutParams Params = (RelativeLayout.LayoutParams)
		// viewHolder.TravelTextBg
		// .getLayoutParams();
		// Params.topMargin = 0;
		// viewHolder.TravelTextBg.setLayoutParams(Params);
		// viewHolder.layoutTravelImage.setVisibility(View.GONE);
		// } else {
		// syncLoadImage(viewHolder.travelImage, model);
		// }
		return convertView;
	}

	private void syncLoadImage(final ImageView imageView, ArticleObj model) {
		syncImageLoader.loadImage(model.icon, new OnImageLoadListener() {

			@Override
			public void onImageLoad(Drawable drawable) {
				if (drawable != null) {
					Bitmap bmp = ImageUtils.drawableToBitmap(drawable);
					Bitmap.Config config = Bitmap.Config.RGB_565;
					float w = bmp.getWidth();
					float h = bmp.getHeight();
					float scale = (float) 9 / 5;
					Rect r = null;
					if (w / h < scale) {
						int top = (int) (h - (5 * w / 9)) / 2;
						r = new Rect(0, top, bmp.getWidth(), bmp.getHeight()
								- top);
					} else {
						int left = (int) (w - (9 * h / 5)) / 2;
						r = new Rect(left, 0, bmp.getWidth() - left, bmp
								.getHeight());
					}
					bmp = ImageUtils.cutBitmap(bmp, r, config);
					// imageView.setBackgroundDrawable(drawable);
					imageView.setImageBitmap(bmp);
				} else {
					imageView
							.setBackgroundResource(R.drawable.default_image_big);
				}
			}

			@Override
			public void onImageLoad(Integer t, Drawable drawable) {

			}

			@Override
			public void onError() {

			}

			@Override
			public void onError(Integer t) {

			}
		});
	}

	public static Bitmap drawableToBitmap(Drawable drawable, int viewWidth,
			int viewHeight) {

		if (((BitmapDrawable) drawable).getBitmap() == null) {
			Log.d("Bitmap", "Bitmap = null");
			return null;
		}
		int imgWidth = ((BitmapDrawable) drawable).getBitmap().getWidth();
		int imgHeight = ((BitmapDrawable) drawable).getBitmap().getHeight();

		// Log.i("View size:", viewWidth+","+viewHeight);
		int x, y, w, h;
		if (imgWidth * viewHeight > viewWidth * imgHeight) {
			h = (int) imgHeight;
			w = (int) (imgHeight * viewWidth / viewHeight);
			y = 0;
			x = (imgWidth - w) / 2;
		} else {
			w = (int) imgWidth;
			h = (int) (imgWidth * viewHeight / viewWidth);
			y = (imgHeight - h) / 2;
			x = 0;
		}
		Bitmap.Config config = Bitmap.Config.RGB_565;
		Bitmap bitmap = Bitmap.createBitmap(
				((BitmapDrawable) drawable).getBitmap(), x, y, w, h);
		return bitmap;
	}

	OnImageLoadListener imageLoadListener = new SyncImageLoader.OnImageLoadListener() {

		@Override
		public void onImageLoad(Integer t, Drawable drawable) {
			View view = mListView.findViewWithTag(t);
			if (view != null) {
				ImageView iv = (ImageView) view
						.findViewById(R.id.TravelDetailImage);
				iv.setAdjustViewBounds(true);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
				iv.setBackgroundDrawable(drawable);
			}
		}

		@Override
		public void onError(Integer t) {
		}

		@Override
		public void onImageLoad(Drawable drawable) {
			// TODO Auto-generated method stub

		}

		@Override
		public void onError() {
			// TODO Auto-generated method stub

		}

	};

	public void loadImage() {
		int start = mListView.getFirstVisiblePosition();
		int end = mListView.getLastVisiblePosition();

		if (end >= getCount()) {
			end = getCount() - 1;
		}
		syncImageLoader.setLoadLimit(start, end);
		syncImageLoader.unlock();
	}

	AbsListView.OnScrollListener onScrollListener = new AbsListView.OnScrollListener() {

		@Override
		public void onScrollStateChanged(AbsListView view, int scrollState) {
			switch (scrollState) {
			case AbsListView.OnScrollListener.SCROLL_STATE_FLING:
				DebugUtil.debug("SCROLL_STATE_FLING");
				syncImageLoader.lock();
				break;
			case AbsListView.OnScrollListener.SCROLL_STATE_IDLE:
				DebugUtil.debug("SCROLL_STATE_IDLE");
				loadImage();
				// loadImage();
				break;
			case AbsListView.OnScrollListener.SCROLL_STATE_TOUCH_SCROLL:
				syncImageLoader.lock();
				break;

			default:
				break;
			}
		}

		@Override
		public void onScroll(AbsListView view, int firstVisibleItem,
				int visibleItemCount, int totalItemCount) {
		}
	};

	public static class ViewHolder {
		TextView travelDate;
		ImageView travelImage;
		TextView travelContentText;
		ImageView travelLineDown;
		RelativeLayout layoutTravelImage, TravelTextBg;
	}
}
